package com.magicstone.common.WatchPoint;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.config.entities.ActionConfig;

import com.magicstone.common.WatchPoint.Watchpoint;

public class DescriptorHelper {
	private final static Log logger = LogFactory.getLog(DescriptorHelper.class);

	public static List<Watchpoint> puarseActions(Map<String, Map<String, ActionConfig>> acs){
		List<Watchpoint> result = new ArrayList<Watchpoint>();
		for(String key : acs.keySet()){
			parseNamespace(result, key, acs.get(key));
		}
		return result;
	}
	
	public static void parseNamespace(List<Watchpoint> ws, String namespace, Map<String, ActionConfig> nsasc) {
		for(String key : nsasc.keySet()){
			ActionConfig ac = nsasc.get(key);
			Watchpoint w = parseAction(namespace, key, ac);
			if(null != w){
				w.setId(ws.size() + 1);
				ws.add(w);
			}
		}
	}
	
	public static Watchpoint parseAction(String namespace, String action, ActionConfig ac) {
		Watchpoint result = new Watchpoint();;
		result.setNamespace(namespace);
		if (null != ac) {
			try {
				Class<?> cl = Class.forName(ac.getClassName());
				String methodName = ac.getMethodName();
				result.setMethod(methodName);
				result.setAction(cl.getSimpleName());

				Method method = null;
				method = cl.getDeclaredMethod(methodName);
				if (null != method) {
					Descriptor des = method.getAnnotation(Descriptor.class);
					if (null != des) {
						result.setDescription(des.description());
						result.setGrade(des.type().toInt());
						result.setResource(des.resource());
					}
				}
			} catch (Exception e) {
				logger.debug(e.getMessage());
			}
		}
		return result;
	}
}
